package com.yumeng.framework.auth.shiro.filter;

import com.yumeng.common.data.enums.AuthClientType;
import com.yumeng.common.data.enums.AuthMode;
import com.yumeng.common.helper.AssertHelper;
import com.yumeng.framework.auth.service.TokenService;
import com.yumeng.framework.auth.shiro.token.MyUsernamePasswordToken;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.util.WebUtils;

/**
 * jwt登录过滤器
 *
 * @author wxd
 * @date 2025/11/13 20:39
 */
@Slf4j
public class JwtLoginFilter extends AbstractLoginStatelessFilter<MyUsernamePasswordToken> {

    public static final String FILTER_NAME = "jwtLoginFilter";

    /** 参数名-用户名 */
    private String usernameParameter = "username";
    /** 参数名-密码 */
    private String passwordParameter = "password";

    public JwtLoginFilter(TokenService tokenService){
        super(tokenService);
    }

    @Override
    protected MyUsernamePasswordToken obtainAuthenticationToken(HttpServletRequest request) {
        String username = WebUtils.getCleanParam(request, usernameParameter);
        String password = WebUtils.getCleanParam(request, passwordParameter);
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new AuthenticationException("认证参数缺失");
        }
        return new MyUsernamePasswordToken(username, password, AuthMode.NORMAL);
    }

    @Override
    protected MyUsernamePasswordToken obtainAuthenticationTokenForJson(HttpServletRequest request) {
        throw new AuthenticationException("暂未实现json格式传参模式");
    }

    @Override
    protected void setExtDetails(MyUsernamePasswordToken authToken, AuthClientType clientType) {
        authToken.setAuthClientType(clientType);
    }

    @Override
    public String getFilteredFlagName() {
        return "myJwtLoginFilter.FILTERED";
    }



    public void setUsernameParameter(String usernameParameter) {
        AssertHelper.assertNotBlank(usernameParameter, "Username parameter must not be empty or null");
        this.usernameParameter = usernameParameter;
    }
    public void setPasswordParameter(String passwordParameter) {
        AssertHelper.assertNotBlank(passwordParameter, "Password parameter must not be empty or null");
        this.passwordParameter = passwordParameter;
    }
}
